<?php namespace App\Http\Controllers\user\uc\ass;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Input;
use Session;
use App\Models\Projects;
use App\Models\EnergyTypes;
use App\Models\ProjectTech;
use App\Models\ProjectDomain;
use App\Models\ProjectMainBody;
use Validator;
use App;
use DB;
use Illuminate\Pagination\LengthAwarePaginator;
use Landish\Pagination\Pagination as BootstrapPresenter;
use App\Models\InvestmentType;
use App\Models\MainBody;
use App\Models\Techs;
use App\Models\Area;
use App\Models\Domains;
use App\Models\ProjectBidding;
use App\Models\ProjectDevice;
use App\Models\ProjectTechnologies;
use App\Models\Devices;
use App\Models\Technologies;



class ProjectController extends Controller {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		//
		$uid = $this->getUid();
		$model = Projects::where("uid", $uid);
		if($model->count())
		{
			$numPerPage = 20;
			$count = $model->count();

			$curPage = (int)Input::get("page");
			if(!$curPage){
				$curPage = 1;
			}
			$p = new LengthAwarePaginator($model, $count, $numPerPage, $curPage);
			$p->setPath("");
	        $presenter = new BootstrapPresenter($p);
	        $data = $model->skip(($curPage - 1) * $numPerPage)->take($numPerPage)->get()->toArray();
		}else{
			$data = array();
			$presenter = '';
		}
		return view("user.uc.ass.project", ["data" => $data])->withPresenter($presenter)->withIsAssProject(true);
	}

	public function addProject()
	{
		return view("user.uc.ass.add_project")->withIsAssProject(true);
	}

	public function editProject()
	{
		$pid = (int)Input::get("pid");
		$uid = $this->getUid();
		$model = Projects::with(['investmentType', 'mainBody', 'projectTech', 'projectDomain', 'projectDomain.domain', 'projectDomain.domain.parent'])->where("id", $pid)->where("uid", $uid);
		if($model->count()){
			$data = $model->get()[0]->toArray();
			$investmentType = InvestmentType::all()->toArray();
			$mainBody 	= MainBody::all()->toArray();
			$techs 		=Techs::all()->toArray();
			$province 	= Area::where("parent_id", 1)->get()->toArray();
			$city 		= Area::where("parent_id", $data['province'])->get()->toArray();
			$area 		= Area::where("parent_id", $data['city'])->get()->toArray();
			$domains 	= Domains::where("parent_id", 0)->get()->toArray();
			$bidding 	= ProjectBidding::with(["user"])->where("project_id", $pid)->get();
			foreach ($bidding as $user) {
				switch ($user["user"]["role_id"]) {
					case env("ENERGY"):
						$user->load("poweruser");
						$user["userData"] = $user["poweruser"]->toArray();
						unset($user["poweruser"]);
						break;
					case env("SAVER"):
						$user->load("energysaver");
						$user["userData"] = $user["energysaver"]->toArray();
						unset($user["energysaver"]);
						break;
					case env("DEVICE_TECH"):
						$user->load("devicetech");
						$user["userData"] = $user["devicetech"]->toArray();
						unset($user["devicetech"]);
						break;
					case env("THIRD"):
						$user->load("thirdparty");
						$user["userData"] = $user["thirdparty"]->toArray();
						unset($user["thirdparty"]);
						break;
					case env("ASSOCIATION"):
						$user->load("association");
						$user["userData"] = $user["association"]->toArray();
						unset($user["association"]);
						break;
					case env("GOVERNMENT");
						$user->load("government");
						$user["userData"] = $user["government"]->toArray();
						unset($user["government"]);
						break;
				}
			}
			$bidding = $bidding->toArray();
			$project_device = ProjectDevice::with("device")->where("project_id", $pid)->get()->toArray();
			$project_tech = ProjectTechnologies::with("technology")->where("project_id", $pid)->get()->toArray();

			$device = Devices::all()->toArray();
			$technology = Technologies::all()->toArray();


		}else{
			return App::abort(404);
		}
		return view("user.uc.ass.edit_project", ['data' => $data, 'investmentType' => $investmentType, 'mainBody' => $mainBody, 'techs' => $techs, 'province' => $province, 'city' => $city, 'area' => $area, 'domains' => $domains, "bidding" => $bidding, "project_device" => $project_device, "project_tech" => $project_tech, "device" => $device, "technology" => $technology])->withIsAssProject(true);
	}

	public function saveProject()
	{
		$rule = [];
		$msg = [];
		$validator = Validator::make(Input::all(), $rule, $msg);
		if($validator->passes()){

			$uid = $this->getUid();
			$data = Input::all();
			$imgArr = Input::only('image');
			$this->moveImages($imgArr, env("PROJECT_DIR"),$uid);
			$data['uid'] = $uid;
			$project = Projects::create($data);
			$techs = Input::get("techs");
			$domains = Input::get("domains");
			foreach ($techs as $tech)
			{
				ProjectTech::create(["cate_id" => $tech, "project_id" => $project->id]);
			}
			foreach ($domains as $domain)
			{
				ProjectDomain::create(["cate_id" => $domain, "project_id" => $project->id]);
			}
			$project_device = Input::get("device");
			$project_tech = Input::get("useTech");
			foreach ($project_device as $value) {
				ProjectDevice::create(["project_id" => $project->id, "device_id" => $value]);
			}
			foreach ($project_tech as $value) {
				ProjectTechnologies::create(["project_id" => $project->id, "tech_id" => $value]);
			}
			$mainBody = Input::get("main_body");
			ProjectMainBody::create(["mb_id" => $mainBody, "project_id" => $project->id]);

			return $this->json([]);

		}else{
			$errors = $validator->messages();
			return self::error('', $errors->first());
		}
	}

	public function updateProject()
	{
		$rule = [];
		$msg = [];
		$validator = Validator::make(Input::all(), $rule, $msg);
		if($validator->passes()){
			$pid = (int)Input::get("pid", 0);
			$uid = $this->getUid();
			$model = Projects::where("id", $pid)->where("uid", $uid);
			if($model->count()){

				$data = Input::except('pid', 'domains', 'techs', 'main_body', 'bidding_id', 'device', 'useTech');
				$imgArr = Input::only('image');
				$this->moveImages($imgArr, env("PROJECT_DIR"));
				$model->update($data);
				$tech_model = ProjectTech::where("project_id", $pid);
				$tech_model->delete();
				$domain_model = ProjectDomain::where("project_id", $pid);
				$domain_model->delete();
				$techs = Input::get("techs");
				$domains = Input::get("domains");
				foreach ($techs as $tech)
				{
					ProjectTech::create(["cate_id" => $tech, "project_id" => $pid]);
				}
				foreach ($domains as $domain)
				{
					ProjectDomain::create(["cate_id" => $domain, "project_id" => $pid]);
				}
				$mainBody = Input::get("main_body");
				$body_model = ProjectMainBody::where("project_id", $pid);
				$body_model->update(["mb_id" => $mainBody]);
				$bidding_id = (int)Input::get("bidding_id");
				if($bidding_id)
				{
					ProjectBidding::where("project_id", $pid)->update(["is_chosen"=> 0]);
					ProjectBidding::where("id", $bidding_id)->update(["is_chosen" => 1]);
				}
				$project_device = ProjectDevice::where("project_id", $pid)->delete();
				$project_tech = ProjectTechnologies::where("project_id", $pid)->delete();

				$project_device = Input::get("device");
				$project_tech = Input::get("useTech");
				foreach ($project_device as $value) {
					ProjectDevice::create(["project_id" => $pid, "device_id" => $value]);
				}
				foreach ($project_tech as $value) {
					ProjectTechnologies::create(["project_id" => $pid, "tech_id" => $value]);
				}

				return $this->json([]);
			}else{
				return;
			}
		}else{
			$errors = $validator->messages();
			return self::error('', $errors->first());
		}
	}


	public function projectList()
	{
		$uid = $this->getUid();
		$data = Projects::where("uid", $uid)->get()->toArray();
		return $this->json(['data' => $data]);
	}

	public function getProjectDetail()
	{
		$pid = Input::get("pid");
		$uid = $this->getUid();
		$model = Projects::with(['investmentType', 'mainBody', 'projectTech', 'projectDomain', 'projectDomain.domain', 'biddings', 'technologies', 'devices'])->where("id", $pid)->where("uid", $uid);
		if($model->count()){
			$data = $model->get()[0]->toArray();
			return $this->json(["data" => $data]);
		}else{
			return;
		}
	}
	public function getProjectAudit(){
  		$pid = Input::get("uid");
  		$state = Input::get("state");
  		$data = Devices::where("id", $did);
  		$data->update(["verify_state" => $state]);
  	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		//
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		//
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}

}
